package com.azt.provider.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.azt.api.pojo.SignUpAdmin;
import com.azt.api.pojo.vo.SignUpAdminVO;
import com.azt.api.service.SignUpAdminService;
import com.azt.model.WeChatUserInfo;
import com.azt.model.page.Pagination;
import com.azt.provider.mapper.SignUpAdminMapper;
import com.azt.service.wechat.WeChatConstant;
import com.azt.service.wechat.WeChatService;
import com.azt.utils.FormatUtil;
import com.azt.utils.Preconditions;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import freemarker.template.utility.StringUtil;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 会议报名管理员信息
 * Created by LiQZ on 2017/3/28.
 */
@Service
public class SignUpAdminServiceImpl implements SignUpAdminService {

    private static final Logger logger = LoggerFactory.getLogger(SignUpAdminServiceImpl.class);

    @Autowired
    private SignUpAdminMapper signUpAdminMapper;


    @Autowired
    private WeChatService weChatService;

    @Override
    public Pagination getPage(int pageNo, int pageSize, Map<String, String> searchMap) {
        Page<Object> startPage = PageHelper.startPage(pageNo, pageSize);
        PageHelper.orderBy("createtime desc");
        List<SignUpAdmin> list = signUpAdminMapper.selectByParams(searchMap);
        List<SignUpAdminVO> voList = Lists.transform(list, new Function<SignUpAdmin, SignUpAdminVO>() {
            @Override
            public SignUpAdminVO apply(SignUpAdmin input) {
                SignUpAdminVO output = new SignUpAdminVO();
                output.setId(input.getId());
                JSONObject obj = JSON.parseObject(input.getWeixin());
                output.setNick(charArrayToString(obj.getString("nick")));
                output.setAvatar(obj.getString("avatar"));
                return output;
            }
        });
        Pagination p = new Pagination(startPage, voList);
        p.setList(voList);
        p.setParams(searchMap);
        return p;
    }

    @Override
    public void delete(String id) {
        signUpAdminMapper.deleteByPrimaryKey(id);
    }

    private static String charArrayToString(String s) {
        String[] tokens = StringUtils.split(s, ",");
        if (ArrayUtils.isEmpty(tokens)) {
            return null;
        }
        char[] charArray = new char[tokens.length];
        int i = 0;
        for (String token : tokens) {
            int ch = FormatUtil.parseInteger(token).intValue();
            charArray[i] = (char) ch;
            i++;
        }
        return String.valueOf(charArray);
    }

    @Override
    public void saveAdmin(String code, String secret) {
        Preconditions.checkArgument(WeChatConstant.SECRET.equals(secret));
        WeChatUserInfo userInfo = weChatService.getUserInfo(code);
        // 判断微信存不存在
        SignUpAdmin admin = signUpAdminMapper.selectByPrimaryKey(userInfo.getUnionId());
        Preconditions.checkArgument(admin == null, "您已经是管理员了");
        admin = new SignUpAdmin();
        JSONObject weixin = new JSONObject();
        weixin.put("avatar", userInfo.getAvatar());
        weixin.put("nick", stringToCharArray(userInfo.getNick()));
        admin.setId(userInfo.getUnionId());
        admin.setWeixin(weixin.toJSONString());
        signUpAdminMapper.insert(admin);
    }

    private static String stringToCharArray(String s) {
        if (StringUtils.isEmpty(s)) {
            return null;
        }
        char[] charArray = s.toCharArray();
        Integer[] intArray = new Integer[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            intArray[i] = Integer.valueOf(charArray[i]);
        }
        return StringUtils.join(intArray, ',');
    }

}
